
package cnhy.salary.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cnhy.salary.mapper.SalaryMapper;
import cnhy.salary.service.WageSvc;
import com.easy.query.core.api.dynamic.sort.ObjectSort;
import com.ruoyi.common.utils.DateUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;
import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import cnhy.salary.domain.MonthlyCfg;
//import cnhy.salary.service.MonthlyCfgService;
import ling.common.*;
import ling.common.domain.*;

 /** 月信息配置记录 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-5-26
 */
 @Slf4j
@Api(tags = "月信息配置记录 功能接口")
@RestController
@RequestMapping("/salary/MonthlyCfg")
public class MonthlyCfgController extends EQueryController<MonthlyCfg>{
    

    
    @ApiOperation("详情")
    @PreAuthorize("@ps.any(@pay.monthlyCfg.query)")
    @GetMapping(value = "/{id}")
    public Result<MonthlyCfg> getInfo(@PathVariable("id") Long id)
    {
       return super.getInfo(id);
    }
    
    @ApiOperation("分页列表")
    @PreAuthorize("@ps.any(@pay.monthlyCfg.list)")
    @GetMapping("list")
    public ResultRows<MonthlyCfg> list(MonthlyCfg dto, PageDomain pageRequest) {

        return queryPage(dto,pageRequest);
    }

     @Override
     protected ResultRows<MonthlyCfg> queryPage(Serializable whereObj, PageDomain pageRequest) {
        var dto=(MonthlyCfg)whereObj;
         gainPageDomain(pageRequest);
         var pitem = queryHelper.query().queryable(MonthlyCfg.class)
                 .whereObject(whereObj != null, whereObj)
                 .where(dto.getMonth()!=null,
                         p->p.rangeClosed(MonthlyCfg::getMonth,DateUtil.beginOfMonth(dto.getMonth()),DateUtil.endOfMonth(dto.getMonth())));
         if (pageRequest instanceof ObjectSort)
             pitem.orderByObject((ObjectSort) pageRequest);
         var pData = pitem.orderByDesc(p->p.column(MonthlyCfg::getId)).toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
         return toResultRows(pData);
     }

     @ApiOperation("新增")
    @PreAuthorize("@ps.any(@pay.monthlyCfg.add)")
    @Log(title = "月信息配置记录", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody MonthlyCfg entity){

        var old=queryHelper.entityQuery(MonthlyCfg.class)
                .where(p->p.month().rangeClosed(DateUtil.beginOfMonth(entity.getMonth()),DateUtil.endOfMonth(entity.getMonth())))
                .where(p->p.lineId().eq(entity.getLineId()))
                .firstOrNull();
        if(old!=null)
            return Result.bad("此月份的产线配置信息已存在！");

        entity.setStatus(0);
         entity.setLv1Final(entity.getLv1());
         entity.setLv2Final(entity.getLv2());
         entity.setLv3Final(entity.getLv3());
        return super.add(entity);
    }
    
    @ApiOperation("删除")
    @PreAuthorize("@ps.any(@pay.monthlyCfg.remove)")
    @Log(title = "月信息配置记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Long[] ids){
        return super.remove(Arrays.stream(ids).toArray());
    }
    
    @ApiOperation("编辑")
    @PreAuthorize("@ps.any(@pay.monthlyCfg.edit)")
    @Log(title = "月信息配置记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public  Result edit(@Validated @RequestBody MonthlyCfg entity){
        var old = queryHelper.entityQuery(MonthlyCfg.class)
                .whereById(entity.getId())
                .where(m -> m.status().in(new Integer[]{0,101})).firstOrNull();
        old.setLv1(entity.getLv1());
        old.setLv2(entity.getLv2());
        old.setLv3(entity.getLv3());
        old.setLv1Final(entity.getLv1());
        old.setLv2Final(entity.getLv2());
        old.setLv3Final(entity.getLv3());
        old.setWorkingDays(entity.getWorkingDays());
        return super.edit(old);
    }
    @Resource
    WageSvc wageSvc;
     @ApiOperation(value = "提交到审批",notes = "示例参数： {id:3,lv1Final:3.0,lv2Final:3.1,lv3Final:3.2}")
     @PreAuthorize("@ps.any(@pay.monthlyCfg.edit)")
     @Log(title = "月信息配置记录", businessType = BusinessType.UPDATE)
     @PostMapping("/submit")
     @Transactional
     public  Result submit(@Validated @RequestBody MonthlyCfg entity) {
         var old = queryHelper.entityQuery(MonthlyCfg.class)
                 .whereById(entity.getId())
                 .where(m -> m.status().in(new Integer[]{0,101}))
                 .firstOrNull();
         old.setLv1Final(entity.getLv1Final());
         old.setLv2Final(entity.getLv2Final());
         old.setLv3Final(entity.getLv3Final());
         old.approval(1,null,null);
         var re=  super.edit(old);
         wageSvc.updateDailyBaseFinal(old);
         return  re;
     }
     @Resource
     SalaryMapper salaryMapper;
     @ApiOperation(value = "审批",notes = "id,status:100通过，101驳回;approvalRecord:审批备注")
     @PreAuthorize("@ps.any('pay.monthlyCfg.approval')")
     @Log(title = "月信息配置记录", businessType = BusinessType.UPDATE)
     @PostMapping("/approval")
     public  Result approval(@Validated @RequestBody MonthlyCfg entity){
         var old = queryHelper.entityQuery(MonthlyCfg.class)
                 .whereById(entity.getId())
                 .where(p->p.status().eq(1))
                 .firstOrNull();
        old.approval(entity.getStatus()==100,entity.getApprovalRecord(),null);
         var map=MapUtil.builder("date",(Object) entity.getMonth()).put("lineId",entity.getLineId()).map();

          super.edit(old);
         salaryMapper.dailyWageUpdateBaseFinal(map);
         return Result.ok();
     }

    
    @ApiOperation("导出")
    @PreAuthorize("@ps.any(@pay.monthlyCfg.export)")
    @Log(title = "月信息配置记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MonthlyCfg entity, PageDomain pageRequest,HttpServletResponse response)
    {
        super.export(entity,pageRequest,null,response);
    }


     public void createMonthlyBaseCfg(Date timeSet) {
         try {
             // 获取上个月的日期
             var lastMonth = timeSet == null ? DateUtils.addDays(new Date(), -1) : timeSet;
             // 查询上个月所有产线的实际基数配置
             var lastMonthCfgs = queryHelper.entityQuery(MonthlyCfg.class)
                     .where(p -> p.month().rangeClosed(DateUtil.beginOfMonth(lastMonth), DateUtil.endOfMonth(lastMonth)))
                     .toList();

             for (var lastCfg : lastMonthCfgs) {
                 // 检查当前月是否已存在配置
                 var existingCfg = queryHelper.entityQuery(MonthlyCfg.class)
                         .where(p -> p.month().rangeClosed(DateUtil.beginOfMonth(DateUtils.addMonths(lastMonth, 1)), DateUtil.endOfMonth(DateUtils.addMonths(lastMonth, 1))))
                         .where(p -> p.lineId().eq(lastCfg.getLineId()))
                         .firstOrNull();
                 
                 if (existingCfg != null) {
                     log.info("产线ID:{} 的当前月配置已存在，跳过创建", lastCfg.getLineId());
                     continue;
                 }
                 
                 // 创建新月的配置
                 var newCfg = new MonthlyCfg();
                 // 设置基本信息
                 newCfg.setId(null);
                 newCfg.setLineId(lastCfg.getLineId());  // 产线ID
                 newCfg.setLineName(lastCfg.getLineName());
                 newCfg.setMonth(DateUtil.beginOfMonth(DateUtils.addMonths(new Date(), 1)));  // 设置为下个月月初
                 newCfg.setStatus(0);  // 状态：未审核

                 // 从上月配置复制数据
                 newCfg.setLv1(lastCfg.getLv1Final());  // 预估基数1
                 newCfg.setLv2(lastCfg.getLv2Final());  // 预估基数2
                 newCfg.setLv3(lastCfg.getLv3Final());  // 预估基数3
                 newCfg.setWorkingDays(lastCfg.getWorkingDays());  // 工作天数

                 // 设置初始实际基数为预估值
                 newCfg.setLv1Final(lastCfg.getLv1Final());
                 newCfg.setLv2Final(lastCfg.getLv2Final());
                 newCfg.setLv3Final(lastCfg.getLv3Final());
                 
                 // 设置创建信息（定时任务不依赖用户上下文）
                 newCfg.setCreatedTime(new Date());
                 newCfg.setCreatedId(1L);  // 使用系统管理员ID
                 
                 // 直接使用queryHelper插入，避免调用需要用户上下文的add方法
                 queryHelper.query().insertable(newCfg).executeRows();
                 log.info("成功创建产线ID:{} 的月度基数配置", newCfg.getLineId());
             }
         } catch (Exception ex) {
             log.error("创建月度基数配置异常", ex);
             throw ex;
         }
     }
}